package com.wjj.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.annotation.UseDataSource;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.wjj.common.core.constant.CacheNames;
import com.wjj.common.core.constant.UserConstants;
import com.wjj.common.core.exception.ServiceException;
import com.wjj.common.core.service.ConfigService;
import com.wjj.common.core.utils.MapstructUtils;
import com.wjj.common.core.utils.SpringUtils;
import com.wjj.common.core.utils.StringUtils;
import com.wjj.common.mybatis.core.page.PageQuery;
import com.wjj.common.mybatis.core.page.TableDataInfo;
import com.wjj.common.redis.utils.CacheUtils;

import com.wjj.system.domain.SysConfig;
import com.wjj.system.domain.bo.SysConfigBo;
import com.wjj.system.domain.vo.SysConfigVo;
import com.wjj.system.mapper.SysConfigMapper;
import com.wjj.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 参数配置 服务层实现
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService, ConfigService {

    @Override
    public TableDataInfo<SysConfigVo> selectPageConfigList(SysConfigBo config, PageQuery pageQuery) {
        QueryWrapper qw = buildQueryWrapper(config);
        Page<SysConfig> paginate = mapper.paginate(pageQuery.build(), qw);
        Page<SysConfigVo> resultPage = new Page<>(paginate.getPageNumber(), paginate.getPageSize(), paginate.getTotalRow());
        resultPage.setRecords(MapstructUtils.convert(paginate.getRecords(), SysConfigVo.class));
        return TableDataInfo.build(resultPage);
    }

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    @UseDataSource("master")
    public SysConfigVo selectConfigById(Long configId) {
        SysConfig sysConfig = mapper.selectOneById(configId);
        return MapstructUtils.convert(sysConfig, SysConfigVo.class);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Cacheable(cacheNames = CacheNames.SYS_CONFIG, key = "#configKey")
    @Override
    public String selectConfigByKey(String configKey) {
        SysConfig retConfig = mapper.selectOneByQuery(QueryWrapper.create().eq(SysConfig::getConfigKey, configKey));
        if (ObjectUtil.isNotNull(retConfig)) {
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取注册开关
     * @return true开启，false关闭
     */
    @Override
    public boolean selectRegisterEnabled() {
        SysConfig retConfig = mapper.selectOneByQuery(QueryWrapper.create().eq(SysConfig::getConfigKey, "sys.account.registerUser"));
        if (ObjectUtil.isNull(retConfig)) {
            return false;
        }
        return Convert.toBool(retConfig.getConfigValue());
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysConfigVo> selectConfigList(SysConfigBo config) {
        QueryWrapper qw = buildQueryWrapper(config);
        List<SysConfig> sysConfigs = mapper.selectListByQuery(qw);
        return MapstructUtils.convert(sysConfigs, SysConfigVo.class);
    }

    private QueryWrapper buildQueryWrapper(SysConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper qw = new QueryWrapper();
        qw.like(SysConfig::getConfigName, bo.getConfigName(), StringUtils.isNotBlank(bo.getConfigName()))
            .eq(SysConfig::getConfigType, bo.getConfigType(), StringUtils.isNotBlank(bo.getConfigType()))
            .like(SysConfig::getConfigKey, bo.getConfigKey(), StringUtils.isNotBlank(bo.getConfigKey()))
            .between(SysConfig::getCreateTime, params.get("beginTime"), params.get("endTime"), params.get("beginTime") != null && params.get("endTime") != null)
            .orderBy(SysConfig::getConfigId);
        return qw;
    }

    /**
     * 新增参数配置
     *
     * @param bo 参数配置信息
     * @return 结果
     */
    @CachePut(cacheNames = CacheNames.SYS_CONFIG, key = "#bo.configKey")
    @Override
    public String insertConfig(SysConfigBo bo) {
        SysConfig config = MapstructUtils.convert(bo, SysConfig.class);
        int row = mapper.insert(config);
        if (row > 0) {
            return config.getConfigValue();
        }
        throw new ServiceException("操作失败");
    }

    /**
     * 修改参数配置
     *
     * @param bo 参数配置信息
     * @return 结果
     */
    @CachePut(cacheNames = CacheNames.SYS_CONFIG, key = "#bo.configKey")
    @Override
    public String updateConfig(SysConfigBo bo) {
        boolean row;
        SysConfig config = MapstructUtils.convert(bo, SysConfig.class);
        if (config.getConfigId() != null) {
            SysConfig temp = mapper.selectOneById(config.getConfigId());
            if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) {
                CacheUtils.evict(CacheNames.SYS_CONFIG, temp.getConfigKey());
            }
            row = this.updateById(config);
        } else {
            CacheUtils.evict(CacheNames.SYS_CONFIG, config.getConfigKey());
            row = this.update(config, QueryWrapper.create()
                .eq(SysConfig::getConfigKey, config.getConfigKey()));
        }
        if (row) {
            return config.getConfigValue();
        }
        throw new ServiceException("操作失败");
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     */
    @Override
    public void deleteConfigByIds(Long[] configIds) {
        for (Long configId : configIds) {
            SysConfig config = this.getById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
                throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
            CacheUtils.evict(CacheNames.SYS_CONFIG, config.getConfigKey());
        }
        this.removeByIds(Arrays.asList(configIds));
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        CacheUtils.clear(CacheNames.SYS_CONFIG);
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyUnique(SysConfigBo config) {
        long configId = ObjectUtil.isNull(config.getConfigId()) ? -1L : config.getConfigId();
        SysConfig info = mapper.selectOneByQuery(QueryWrapper.create().eq(SysConfig::getConfigKey, config.getConfigKey()));
        if (ObjectUtil.isNotNull(info) && info.getConfigId() != configId) {
            return false;
        }
        return true;
    }

    /**
     * 根据参数 key 获取参数值
     *
     * @param configKey 参数 key
     * @return 参数值
     */
    @Override
    public String getConfigValue(String configKey) {
        return SpringUtils.getAopProxy(this).selectConfigByKey(configKey);
    }

}
